package com.dataseek.iot.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dataseek.iot.sys.entity.Menu;
import com.dataseek.iot.sys.service.MenuService;
import com.dataseek.iot.sys.service.SysService;
import com.dataseek.iot.toolikit.common.response.ResponseResult;
import com.dataseek.iot.sys.vo.UserVo;
import com.dataseek.iot.toolkit.auth.entity.LoginUser;
import com.dataseek.iot.toolkit.auth.entity.SysUser;
import com.dataseek.iot.toolkit.auth.redis.config.RedisCache;
import com.dataseek.iot.toolkit.auth.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class SysServiceImpl implements SysService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MenuService menuService;

    @Override
    public ResponseResult login(UserVo userVo) {
        //AuthenticateManager 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userVo.getUsername(),userVo.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过,使用userid生成jwt,jwt存入ResponseResult返回
        LoginUser loginUser=(LoginUser)authenticate.getPrincipal();
        String userid = loginUser.getSysUser().getUserId().toString();
        String tenantCode = loginUser.getSysUser().getTenantCode();
        List<String> permissions = loginUser.getPermissions();
        String jwt = JwtUtil.createJWT(tenantCode+"~"+userid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId",userid);
        jsonObject.put("companyCode",tenantCode);
        //将用户完整信息存入redis,userid作为key
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        //List<Menu> menuList = menuService.queryMenuTree(Long.parseLong(userid));
        map.put("permissions",permissions);
        map.put("user",jsonObject);
        redisCache.setCacheObject(tenantCode+"~"+userid,loginUser,1, TimeUnit.DAYS);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser sysUser=loginUser.getSysUser();
        Long userid = sysUser.getUserId();
        String tenantCode = sysUser.getTenantCode();
        //删除redis中的值
        redisCache.deleteObject(tenantCode+"~"+userid);
        return new ResponseResult(200,"注销成功");
    }
}
